const os = require("os");
const config = require("../db/config");
const httpUtils = require("./httpUtils");

const TAG = "[网络工具]";
const network = {
    /**
     * 获取本地ip
     */
    getLocalIP: function () {
        const ifaces = os.networkInterfaces();
        let ip = 'localhost';
        Object.keys(ifaces).forEach(function (ifname) {
            let alias = 0;
            ifaces[ifname].forEach(function (iface) {
                if ('IPv4' !== iface.family || iface.internal !== false) {
                    return;
                }
                if (alias >= 1) {
                    ip = iface.address;
                } else {
                    ip = iface.address;
                }
                ++alias;
            });
        });
        return ip;
    },
    // 获取外网ip
    getPublicIP:async function () {
        const ret = await httpUtils.get(config.getIpUrl);

        if (ret && ret.data) {
            if(ret.data.ip) {
                return ret.data.ip;
            }else{
                return ret.data;
            }
        } else {
            return ret.ip;
        }
    },
    // 设置配置的ip
    setConfigIp:async function () {
        // 自身的外网ip
        if (!config.publicIp) {
            try {
                config.publicIp = await this.getPublicIP();
                console.info(TAG, "获取到外网IP:", config.publicIp);
            } catch (e) {
                console.error(TAG, "获取外网IP异常", e);
            }
        }
        // 内网ip
        if (!config.localIp) {
            try {
                config.localIp = this.getLocalIP();
                console.info(TAG, "获取到内网IP:", config.localIp);
            } catch (e) {
                console.error(TAG, "获取内网IP异常", e);
            }
        }
    }
};
module.exports = network;
